package src.week4.PP611;



import src.week2.EmptyCollectionException;
import src.week4.*;

public class LinkedOrderedList<T> extends LinkedList<T> implements OrderedListADT<T>
{
    protected int count;
    protected LinearNode<T> head,tail;
    protected int modCount;

    public LinkedOrderedList()
    {
        count = 0;
        head=tail=null;
        modCount=0;
    }

    @Override
    public void add(T element)
    {

        LinearNode<T> temp = new LinearNode(element);
        LinearNode<T> previous = null;
        LinearNode<T> current = head;
        while(current != null && Integer.parseInt(element+"") > Integer.parseInt(current.getElement()+"")){
            previous = current;
            current = current.getNext();
        }
        if(previous == null){
            head = tail =  temp;
        }
        else{
            previous.setNext(temp);
        }
        temp.setNext(current);
        if(temp.getNext() == null) {
            tail = temp;
        }
        count++;
        modCount++;
    }
    @Override
    public T remove(T targetElement){
        if (isEmpty()) {
            throw new EmptyCollectionException("LinkedList");
        }
        boolean found = false;
        LinearNode<T> previous = null;
        LinearNode<T> current = head;
        while (current != null && !found)
            if (targetElement.equals(current.getElement()))
                found = true;
            else {
                previous = current;
                current = current.getNext();
            }
        if (!found)
            throw new ElementNotFoundException("LinkedList");
        if (size() == 1)
            head = tail = null;
        else if (current.equals(head))
            head = current.getNext();
        else if (current.equals(tail))
        {
            tail = previous;
            tail.setNext(null);
        } else
            previous.setNext(current.getNext());
        count--;
        modCount++;
        return current.getElement();
    }

    @Override
    public T removeFirst() {
        return null;
    }

    @Override
    public T removeLast() {
        return null;
    }

    @Override
    public T first() {
        return null;
    }

    @Override
    public T last() {
        return null;
    }

    @Override
    public boolean contains(T target) {
        LinearNode temp=head;
        while ((temp.getElement()!=target)){
            temp=temp.getNext();
        }
        return temp.getElement() == target;
    }

    @Override
    public boolean isEmpty() {
        return count==0;
    }

    @Override
    public int size() {
        return count;
    }
}
